package com.lv.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lv.mapper.TbContentMapper;
import com.lv.pojo.TbContent;
import com.lv.service.ContentService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@DubboService
public class ContentServiceImpl implements ContentService {

    @Resource
    private TbContentMapper cm;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<TbContent> getInfo() {
        return cm.selectByExample(null);
    }

    @Override
    public int insert(TbContent t) {
        return cm.insertSelective(t);
    }

    @Override
    public TbContent getById(Long id) {
        return cm.selectByPrimaryKey(id);
    }

    @Override
    public int update(TbContent t) {
        return cm.updateByPrimaryKeySelective(t);
    }

    @Override
    public int delete(Long id) {
        return cm.deleteByPrimaryKey(id);
    }

    @Override
    public int deleteCheck(Long[] ids) {
        for (Long id : ids) {
            delete(id);
        }
        return 1;
    }

    @Override
    public List<TbContent> getContentByCategoryId(Integer categoryId, Integer pageSize) {
        String contentList = (String) stringRedisTemplate.boundValueOps("content" + categoryId).get();
        if(contentList==null || "".equals(contentList)){
            List<TbContent> contentByCategoryId = cm.getContentByCategoryId(categoryId, pageSize);
            String s = JSONObject.toJSONString(contentByCategoryId);
            stringRedisTemplate.opsForValue().set("content"+categoryId,s);
            return contentByCategoryId;
        }
        return (List<TbContent>) JSONObject.parse(contentList);
    }
}
